package cn.liwq.demo.aspect;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lweiqiang
 * @date 2023/3/2
 */
@Slf4j
@Aspect
@Component
@ConditionalOnWebApplication
public class ControllerAspect {

  @Resource
  private ObjectMapper objectMapper;

  @Pointcut("execution(public * cn.liwq.*.controller.*.*(..))")
  public void controllerMethod() {
  }

  @Before("controllerMethod()")
  public void beforeMethod(JoinPoint joinPoint) {
    if (Objects.isNull(joinPoint)) {
      return;
    }
    try {
      Signature signature = joinPoint.getSignature();
      if (Objects.nonNull(signature)) {
        StringBuilder sb = new StringBuilder();
        sb.append(StrUtil.format("进入方法：{}#{}", signature.getDeclaringTypeName(), signature.getName()));
        Object[] args = joinPoint.getArgs();
        if (args != null) {
          sb.append(",入参：").append(objectMapper.writeValueAsString(args));
          log.debug(sb.toString());
        }
      }
    } catch (Exception e) {
      // ignore
    }
  }
}
